jClass = {
    initPage() {
        this.loadFont();
        window.onresize=this.loadFont;

        this.tableOneTitleObj = {
            networkLv: '入网率', networkLvScore: '入网率得分',
            onlineLv: '上线率', onlineLvScore: '上线率得分',
            footprintLv: '轨迹完整率', footprintLvScore: '轨迹完整率得分',
            dataQualifiedLv: '数据合格率', dataQualifiedLvScore: '数据合格率得分',
            alarmHandleLv: '报警平均处理率', alarmHandleLvScore: '报警平均处理率得分',
            vehicleDriftLv: '卫星定位车辆漂移率', vehicleDriftLvScore: '卫星定位车辆漂移率得分',
            superviseHandleLv: '督办处理率', superviseHandleLvScore: '督办处理率得分',
            alarmHandleTime: '报警平均处理时长', alarmHandleTimeScore: '报警平均处理时长得分',
            overSpeedCount: '平均车辆超速次数', overSpeedCountScore: '平均车辆超速次数得分',
            tiredDrivingTime: '平均疲劳驾驶时长', tiredDrivingTimeScore: '平均疲劳驾驶时长得分',
            platformConnectivityLv: '平台连通率', platformConnectivityLvScore: '平台连通率得分',
            responseLv: '查岗响应率', responseLvScore: '查岗响应率得分'
        }

        this.tableDwonTitleObj = {
            netCarLv: '班线客运', netTransLv: '旅游包车', netDangerLv: '危险品运输'
        }

        this.data = {
            tabParams: {
                page: 1,
                size: 15,
                assessType: 1 // 1 地区 2 平台 3 企业
            },
            tableParams: {
                areaId: '',
                owersName: '',
                platformName: '',
                dateType: 3,
                time: '2019-09-01',
                page: 1,
                size: 10,
                assessType: 1 // 1-平台，2-地区，3-企业
            },
            tabRemark: 'zong',
            tabShowc: ''
        }
        this.init()
        this.bindEvent();
    },
    loadFont(){
        var widthScreen = $(window).width();
        var nowFont=widthScreen/1920*15;
        var htmlFont=document.getElementsByTagName('html')[0];
        htmlFont.style.fontSize =nowFont+"px";
        htmlFont.style.lineHeight =nowFont+"px";
    },
    init() {
        let that = this

        $('#selectedOption').siblings("input").val('月')
        var now = new Date();
        let curYear = now.getFullYear();
        let curMonth = now.getMonth() + 1;
        let curDate = now.getDate();
        let maxCurMonth = curMonth - 1 >= 10 ? curMonth - 1 : `0${curMonth - 1}`;
        let curTime = `${curYear}-${maxCurMonth}-01`;
        // console.log(curTime, "ccccccccc")
        that.data.tableParams.time = curTime;
        lay('#version').html('-v' + laydate.v);
        $Date = laydate;
        that.initDateForm();

        this.selectedValue()

        // 地区下拉框
        this.diquSelceted();

        // 设置顶部tab
        var sId = window.location.hash;
        // console.log(sId)
        let lihtml = ''
        if (sId === '#regionalAssessment') {
            this.data.tabParams.assessType = 1
            lihtml = '<li class="active" data-remark="zong">地区考核统计</li>'
            $('#input_qy').hide()
            $('#input_pt').hide()
            this.data.tableParams.assessType = 1
        } else if(sId === '#regionalAssessment_platform') {
            this.data.tabParams.assessType = 2
            lihtml = '<li class="active" data-remark="zong">平台考核统计</li>'
            $('#input_qy').hide()
            $('#input_dq').hide()
            this.data.tableParams.assessType = 2
        } else if(sId === '#regionalAssessment_buss') {
            this.data.tabParams.assessType = 3
            lihtml = '<li class="active" data-remark="zong">企业考核统计</li>'
            $('#input_pt').hide()
            $('#input_dq').hide()
            this.data.tableParams.assessType = 3
        }

        this.getOneTable()
        $("#jline_chart").hide()

        jrequest.get("/api/assess-criterions", this.data.tabParams).then(res => {
            // console.log(res.data)
            res.data.forEach(item => {
                lihtml += `<li data-remark=${item.remark} data-showc=${item.show}>${item.title}</li>`
            })
            $("#jtab ul").html(lihtml)

            // 点击tab切换
            $("#jtab ul li").on('click',function(){
                $(this).addClass("active").siblings("li").removeClass("active");
                that.searchReset()
                $("#jline_chart").hide()
                $('#jtable_div').show()
                let remark = $(this).data('remark')
                that.data.tabRemark = remark
                if (remark === 'zong') {
                    that.getOneTable()
                    return
                }
                $('#jtop_table').show()
                let showc = $(this).data('showc')
                if (showc === '平台连通率' || showc === '查岗响应率') {
                    $('#jtable_div').hide()
                    $("#jline_chart").show()
                    that.setLineCharts(remark)
                    return
                }
                that.data.tabShowc = showc
                that.getXiangTable(remark,showc)

            })
        })
    },
    setLineCharts(remark) {
        var chartName= [""];
        var chartColor= [['#E1E02C','#DB5134']];
        // var  myChart = echarts.init(document.getElementById('jline_chart'));
        // myChart.clear();
        // let chartsxAxis = ["2019-10-07","2019-10-08","2019-10-09","2019-10-10","2019-10-11","2019-10-12","2019-10-13"]
        // let chartCount = [[0,5,100,200,500,9,3]]
        // myChart.setOption(charts.LinesArea(chartName,chartsxAxis,chartCount,chartColor));

        jrequest.get(remark, this.data.tableParams).then(res => {
            let chartsxAxis = []
            let chartCount = [[]]
            res.data.forEach(item => {
                chartsxAxis.push(item.platformName)
                chartCount[0].push(item.rate)
            })
            var  myChart = echarts.init(document.getElementById('jline_chart'));
            myChart.clear();
            myChart.setOption(charts.LinesArea(chartName,chartsxAxis,chartCount,chartColor,'率%'));
        })

    },
    bindEvent() {
        let that = this
        $("#searchClick").click(() => {
            if(this.data.tabRemark === 'zong') {
                this.getOneTable()
            } else {
                this.getXiangTable(this.data.tabRemark,this.data.tabShowc)
            }
        })

        $('#resetClick').click(() => {
            this.searchReset()
        })

        //日期插件下拉选择
        function creatOption() {
            $("#selectedOption").change(function () {
                var index = $(this).find("option:selected").val();
                var indexType = String($(this).get(0).selectedIndex + 1);
                that.data.tableParams.dateType = indexType;
                if (index == "w") {
                    $("#d121").show();
                    $("#worldId").hide();
                } else {
                    $("#worldId").show();
                    $("#worldId").val();
                    $("#d121").hide();
                }
            })
        }
        creatOption();
    },
    searchReset() {
        this.data.tableParams = {
            areaId: '',
            owersName: '',
            platformName: '',
            dateType: 3,
            time: '2019-09-01',
            page: 1,
            size: 10,
            assessType: 1 // 1-平台，2-地区，3-企业
        }
        this.data.tableParams.assessType = this.data.tabParams.assessType
        $(".item.rtable_input").find("input").val("")
        $('input').val("")

        lay('#version').html('-v' + laydate.v);
        $("#selectedOption").val('m');
        $('#selectedOption').siblings("input").val('月')
        var index = $("#selectedOption").find("option:selected").val();
        this.data.tableParams.dateType = "3";
        if (index == "w") {
            $("#d121").show();
            $("#worldId").hide();
        } else {
            $("#worldId").show();
            $("#d121").hide();
        }

        //初始化时间默认为上个月
        var now = new Date();
        let curYear = now.getFullYear();
        let curMonth = now.getMonth() + 1;
        let curDate = now.getDate();
        let maxCurMonth = curMonth - 1 >= 10 ? curMonth - 1 : `0${curMonth - 1}`;
        let curTime = `${curYear}-${maxCurMonth}-01`;
        this.data.tableParams.time = curTime;
        $Date = laydate;
        this.initDateForm();
    },
    selectedValue:function(){
        let optionArr=[{name:'日',value:'d'},{name:'周',value:'w'},{name:'月',value:'m'},{name:'季',value:'s'},{name:'年',value:'y'}];
        this.creatId("#selectedOption",optionArr);
    },
    creatId:function(id,optionArr){
        $(id).html();
        var str="";
        $.each(optionArr,function (i) {
            str+=`<option value=${optionArr[i].value}>${optionArr[i].name}</option>`
        });
        // $(id).html(str);
        $(id).comboSelect();
    },
    getInputVal() {
        if ($(".item.rtable_input").find("input").val()) this.data.tableParams.areaId = $(".item.rtable_input").find("input").attr("data-id")
        else this.data.tableParams.areaId = ''

        this.data.tableParams.platformName = $("#input_pt input").val()
        this.data.tableParams.owersName = $("#input_qy input").val()
    },
    // 入网率/处理率/完整率....
    getXiangTable(remark,showc) {
        let that = this
        let columns = []
        let columnsTop = []
        columns.push({
            title : '序号',
            formatter: function (value, row, index) {
                //获取每页显示的数量
                var pageSize = that.data.tableParams.size;
                //获取当前是第几页
                var pageNumber = that.data.tableParams.page;
                //返回序号，注意index是从0开始的，所以要加上1
                return pageSize * (pageNumber - 1) + index + 1;
            }
        })
        if(that.data.tableParams.assessType === 1) {
            columns.push({field: 'areaName', title: '地区'})
        } else if(that.data.tableParams.assessType === 2) {
            columns.push({field: 'areaName', title: '平台'})
        } else if(that.data.tableParams.assessType === 3) {
            columns.push({field: 'areaName', title: '企业'})
        }
        this.getInputVal()
        jrequest.get(remark, that.data.tableParams).then(res => {
            let columnres = Object.keys(res.data.data.records[0])
            columnres.forEach(item => {
                if (that.tableDwonTitleObj[item]) {
                    let columnobj = {}
                    columnobj.field = item
                    columnobj.title = `${that.tableDwonTitleObj[item]}${showc}`
                    columnobj.formatter = ((value, row, index) => {
                        if (value == '9999') {
                            return '-'
                        } else {
                            if(showc.indexOf('率') !== -1 && showc.indexOf('得分') === -1) {
                                return `${value}%`;
                            } else if(showc.indexOf('次数') !== -1) {
                                return `${value}次`;
                            } else if(showc.indexOf('时长') !== -1) {
                                return `${value}分钟`;
                            } else if(showc.indexOf('得分') !== -1) {
                                    return `${value}分`;
                            }else {
                                return value
                            }
                        }
                    })
                    columns.push(columnobj)
                    columnsTop.push(columnobj)
                }
            })
            let hbColunms = {
                field: "linkRelative",
                title: "环比",
                visible: true,
                formatter: function (value, row, index) {
                    row.compareNum = value;
                    if (value == 0) {
                        return `-`;
                    } else if (value == 9999) {
                        return ``;
                    } else {
                        return `${value}%`;
                    }
                },
                cellStyle: function (value, row, index) {
                    // console.log(row.compareNum, "测试测试测试")
                    // console.log(row, "测试测试测试")
                    let valRow = row.compareNum;
                    if (index % 2 == 0) {
                        if (valRow > 0 && valRow < 9999) {
                            return { css: { "background": "url('img/arrow-top.png') no-repeat 60% center", "background-size": "5px 15px" } }
                        } else if (valRow < 0) {
                            return { css: { "background": "url('img/arrow-bot.png') no-repeat 60% center", "background-size": "5px 15px" } }
                        } else if (valRow == 9999) {
                            return { css: { "background": "url('img/arrow-top.png') no-repeat 60% center", "background-size": "5px 15px" } }
                        } else {
                            return {}
                        }
                    } else {
                        if (valRow > 0 && valRow < 9999) {
                            return { css: { "background": "#042b3e url('../img/arrow-top.png') no-repeat 60% center", "background-size": "5px 15px" } }
                        } else if (valRow < 0) {
                            return { css: { "background": "#042b3e url('img/arrow-bot.png') no-repeat 60% center", "background-size": "5px 15px" } }
                        } else if(valRow == 9999){
                            return { css: { "background": "#042b3e url('../img/arrow-top.png') no-repeat 60% center", "background-size": "5px 15px" } }
                        }else {
                            return {}
                        }
                    }
                }
            }
            columns.push(hbColunms)
            columnsTop.push(hbColunms)
            // console.log(columns)
            $("#jtable_zong").bootstrapTable('destroy');
            that.bindTable('jtable_zong',columns,false,res.data.data.records,res.total,true,'lv')

            $("#jtable_top").bootstrapTable('destroy');
            that.bindTable('jtable_top',columnsTop,false,new Array(res.data),1,false,'lv')
        })
    },
    // 地区/企业/业户考核统计
    getOneTable() {
        $('#jtop_table').hide()
        $("#jid_loading").show()
        let that = this
        this.getInputVal()
        jrequest.get("/api/vehicle/areaStatistics", this.data.tableParams).then(res => {
            // console.log(res.data)
            let columnres = Object.keys(res.data[0])
            let columns = []
            columns.push({
                title : '序号',
                formatter: function (value, row, index) {
                    //获取每页显示的数量
                    var pageSize = that.data.tableParams.size;
                    //获取当前是第几页
                    var pageNumber = that.data.tableParams.page;
                    //返回序号，注意index是从0开始的，所以要加上1
                    return pageSize * (pageNumber - 1) + index + 1;
                }
            })
            if(this.data.tableParams.assessType === 1) {
                columns.push({field: 'areaName', title: '地区'})
            } else if(this.data.tableParams.assessType === 2) {
                columns.push({field: 'areaName', title: '平台'})
            } else if(this.data.tableParams.assessType === 3) {
                columns.push({field: 'areaName', title: '企业'})
            }
            // columns.push({field: 'areaName', title: '地区'})
            columnres.forEach(item => {
                if (res.data[0][item] !== null) {
                    if (this.tableOneTitleObj[item]) {
                        let columnobj = {}
                        columnobj.field = item
                        columnobj.title = this.tableOneTitleObj[item]
                        columnobj.formatter = ((value, row, index) => {
                            if (value == '9999') {
                                return '-'
                            } else {
                                if(this.tableOneTitleObj[item].indexOf('率') !== -1 && this.tableOneTitleObj[item].indexOf('得分') === -1) {
                                    return `${value}%`;
                                } else if(this.tableOneTitleObj[item].indexOf('次数') !== -1) {
                                    return `${value}次`;
                                } else if(this.tableOneTitleObj[item].indexOf('时长') !== -1) {
                                    return `${value}分钟`;
                                } else if(this.tableOneTitleObj[item].indexOf('得分') !== -1) {
                                    return `${value}分`;
                                }else {
                                    return value
                                }
                            }
                        })
                        if (item.indexOf('Score') !== -1) columnobj.visible = false
                        columns.push(columnobj)
                        // console.log(this.tableOneTitleObj[item])
                    }
                }
            })
            columns.push(
                {field: 'totalScore',
                title: '总考核得分',
                formatter: (value,row,index) => {return `${value}分`}
            })
            // console.log(columns)
            $("#jid_loading").hide()
            $("#jtable_zong").bootstrapTable('destroy');
            this.bindTable('jtable_zong',columns,true,res.data,res.total,true,'zong')
        })
    },
    // id 列 是否有隐藏的咧 数据 总条数 是否显示分页 分页方法
    bindTable:function(id,columns,showColumns,data,total,pageShow,nextPageFun){
        if (id === 'jtable_top') {
            console.log(columns)
            console.log(data)
        }
        let that = this
        $('#' + id).bootstrapTable({
            method: 'get',
            cache: false,
            height: 320,
            pagination: pageShow,
            pageSize: that.data.tableParams.size,
            pageNumber:that.data.tableParams.page,
            showColumns: showColumns,
            striped: true,
            columns: columns,
            sidePagination: 'server', // client or server
            totalRows: total,
            data :data,
            onPageChange: function (size, number) {
                // console.log(number)
                that.data.tableParams.page = number
                that.data.tableParams.size = size
                if (nextPageFun === 'zong') {
                    that.getOneTable()
                } else if (nextPageFun === 'lv') {
                    that.getXiangTable()
                }

            },
            formatNoMatches: function(){
                return '暂无数据';
            }
        });
    },
    /**
     * 请求地区数据
     * */
    diquSelceted: function() {
        jrequest.get("/api/assessMent/selectByArea",{}).then(res => {
            let data = res.data
            data[0].code = 1;
            $.each(data[0].cityAreaVOS, function(i, dom) {
                data[0].cityAreaVOS[i].code = 2;
                $.each(data[0].cityAreaVOS[i].cityAreaVOS, function(j, dom) {
                    data[0].cityAreaVOS[i].cityAreaVOS[j].code = 3;
                })
            })
            this.creatMainRido("alarm_qrm_main", data, "cityAreaVOS", "code");
        })
    },
    /**
     * 下拉框
     * */
    creatMainRido: function(id, attr, child, jibie) {
        $(id).html("");
        var sttrdiv = "";
        for(var i = 0; i < 3; i++) {
            sttrdiv += "<div class='qrm-border" + (i + 1) + "' style='display:none'>" +
                "<ul class='qrm-lev-" + (i + 1) + " qrm-lev' id='qrm-border1'>" +
                "</ul>" +
                "</div>"
        };
        $(".qrm-main").html(sttrdiv);
        var str = "";
        $("#qrm-border1").html("");
        var forTree = function(o) {
            for(var i = 0; i < o.length; i++) {
                var urlstr = "";
                try {
                    urlstr = "<li><span data-id='" + o[i]["id"] + "'>" + o[i]["name"] + "</span><i class='qrm-arrow-right'></i><ul class='li-zi-" + o[i][jibie] + "' style='display: none'>";
                    str += urlstr;
                    if(o[i][child] != null) {
                        forTree(o[i][child]);
                    }
                    str += "</ul>";
                } catch(e) {}
            }
            return str;
        };
        $("#qrm-border1").html(forTree(attr));
    },
    //--------------------------------------------日期插件------------------------------------------//
    /**
     * 季度初始化
     * @param ohd 季度input dom对象非jquery对象
     * @param sgl 有值单个，无值默认范围
     */
    renderSeasonDate: function (ohd, sgl) {
        let self = this;
        var ele = $(ohd);
        // console.log(ohd, sgl, "季度")
        var now = new Date();
        let curYear = now.getFullYear();
        let curMonth = now.getMonth() + 1;
        let curDate = now.getDate();
        let maxMonthAuton;
        if (curMonth >= 1 && curMonth <= 3) {
            maxMonthAuton = '0';
        } else if (curMonth >= 4 && curMonth <= 6) {
            maxMonthAuton = '01';
        } else if (curMonth >= 7 && curMonth <= 9) {
            maxMonthAuton = '02';
        } else {
            maxMonthAuton = '03';
        }
        $Date.render({
            elem: ohd,
            type: 'month',
            format: 'yyyy年M季度',
            min: "1900-1-1",
            max: `${curYear}-${maxMonthAuton}-${curDate}`,
            btns: ['clear', 'confirm'],
            ready: function (value, date, endDate) {
                // console.log(value, date, endDate, "季度获取的值")
                var hd = $("#layui-laydate" + ele.attr("lay-key"));
                if (hd.length > 0) {
                    hd.click(function () {
                        ren($(this));
                    });
                }
                ren(hd);
            },
            done: function (value, date) {
                // console.log(value, date, "季度")
                let realMonth;
                if( date.month == "04"){
                    realMonth= '10';
                }else if(date.month == "03"){
                    realMonth= '07';
                }else if(date.month == "02"){
                    realMonth= '04';
                }else{
                    realMonth= '01';
                }
                let time = `${date.year}-${realMonth}-${date.date}`;
                // console.log(time, "ttttttttttttttttttt");
                self.data.tableParams.time = time;
                // console.log(self.data.tableParams.time, "季度赋值");
            }
        });
        var ren = function (thiz) {
            var mls = thiz.find(".laydate-month-list");
            mls.each(function (i, e) {
                $(this).find("li").each(function (inx, ele) {
                    var cx = ele.innerHTML;
                    if (inx < 4) {
                        ele.innerHTML = cx.replace(/月/g, "季度");
                    } else {
                        ele.style.display = "none";
                    }
                });
            });
        }
    },
    /**
     * 初始化表单中年季月日范围选择
     * 下拉框与日期框对应：
     *  <select class="dateSelector" date-target="PI" ...
     *  <input type="text" class="dateTargetPI" readonly ...
     *  PI为自定义的对应关键字
     *
     * @param form 要渲染的form的jquery对象，当form为空默认值为全页面
     * @param sgl 有值单个，无值默认范围
     */
    initDateForm: function (sgl, form) {
        let self = this;
        var now = new Date();
        let curYear = now.getFullYear();
        let curMonth = (now.getMonth() + 1) >= 10 ? now.getMonth() + 1 : `0${now.getMonth() + 1}`;
        let curDate = now.getDate();
        // console.log(curYear, curMonth, curDate, "多去当前年月日")
        let curTime = `${curYear}-${curMonth}-${curDate}`;
        // console.log(curTime, "当前年月日")
        let maxCurYear = curYear - 1;
        let maxCurMonth = (curMonth - 1) >= 10 ? curMonth - 1 : `0${curMonth - 1}`;
        let maxCurDate = curDate - 1;
        if (this.isNull(form)) form = $(document.body);
        var ltm = function (tar, tars, tva) {
            // console.log(tar, tars, tva, "ttttttttttttt")
            tars.each(function () {
                $(this).removeAttr("lay-key");
                this.outerHTML = this.outerHTML;
            });
            tars = form.find(".dateTarget" + tar);
            tars.each(function () {
                var ele = $(this);
                if ("y" == tva) {
                    let maxYearValue = `${maxCurYear}-${curMonth}-${curDate}`;
                    $Date.render({
                        elem: this,
                        type: 'year',
                        format: 'yyyy年',
                        max: maxYearValue,
                        done: function (value, date) {
                            // console.log(value, date, "年");
                            let time = `${date.year}-01-01`;
                            // console.log(time, "ttttttttttttttttttt");
                            self.data.tableParams.time = time;
                            // console.log(self.data.tableParams.time, "月份赋值");
                        }
                    });
                } else if ("s" == tva) {
                    self.renderSeasonDate(this, 1);
                } else if ("m" == tva) {
                    let maxMonthValue = `${curYear}-${maxCurMonth}-${curDate}`;
                    $Date.render({
                        elem: this,
                        type: 'month',
                        format: 'yyyy年MM月',
                        max: maxMonthValue,
                        value: `${curYear}年${maxCurMonth}月`,
                        done: function (value, date) {
                            // console.log(value, date, "月")
                            let monthStr = date.month >= 10 ? date.month : `0${date.month}`;
                            let time = `${date.year}-${monthStr}-01`;
                            // console.log(time, "ttttttttttttttttttt");
                            self.data.tableParams.time = time;
                            // console.log(self.data.tableParams.time, "月份赋值")
                        }
                    });
                } else if ("d" == tva) {
                    let maxDateValue = `${curYear}-${curMonth}-${maxCurDate}`;
                    $Date.render({
                        elem: this,
                        format: 'yyyy年MM月dd日',
                        max: maxDateValue,
                        done: function (value, date) {
                            // console.log(value, date, "日");
                            let monthStr = date.month >= 10 ? date.month : `0${date.month}`;
                            let dateStr = date.date >= 10 ? date.date : `0${date.date}`;
                            let time = `${date.year}-${monthStr}-${dateStr}`;
                            // console.log(time, "ttttttttttttttttttt");
                            self.data.tableParams.time = time;
                            // console.log(self.data.tableParams.time, "月份赋值")
                        }
                    });
                }
            });
        }
        var sels = form.find(".dateSelector");
        sels.each(function (i, e) {
            var ths = this;
            var thiz = $(e);
            var tar = thiz.attr("date-target");
            thiz.next().find("dd").click(function () {
                var tva = thiz.val();
                var tars = form.find(".dateTarget" + tar);
                ltm(tar, tars, tva);
            });
            thiz.change(function () {
                var tva = $(this).val();
                var tars = form.find(".dateTarget" + tar);
                ltm(tar, tars, tva);
            });
            var tars = form.find(".dateTarget" + tar);
            ltm(tar, tars, thiz.val());
        });
    },

    isNull: function (s) {
        if (s == null || typeof (s) == "undefined" || s == "") return true;
        return false;
    },
    week: function () {
        // this.data.tableParams.time = $dp.$('d121').value;
        $dp.$('d121').value = $dp.cal.getP('y') + "年" + $dp.cal.getP('W', 'WW') + "周";
    }
}
$(function() {
    jClass.initPage()


})



















